import { ManageEquipment } from '../../interface/interface';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { NotificationService, BullySubjectService, MessagesService } from 'app/shared/service';
import { Component, OnInit, Input, Output, EventEmitter, OnDestroy, AfterViewInit } from '@angular/core';
import { EquipmentService } from '../../equipment.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { SystemService } from 'app/service/system.service';
import { AuthService } from 'app/auth/auth.service';
import { MESSAGE_CHANNEL } from 'app/app.constants';
import { Subscription } from 'rxjs';
import { IncidentService } from 'app/pages/traffic-management/incident-record/incident.service';

@Component({
    selector: 'itmp-add-equipment',
    templateUrl: './add-equipment.component.html',
    styleUrls: ['./add-equipment.component.css']
})
export class AddEquipmentComponent implements OnInit, OnDestroy, AfterViewInit {
    private _optionList = [];
    isOkLoading = false;
    @Input() visible = false;
    @Input() title = '';
    @Input() selectionList: any;
    @Output() visibleChange = new EventEmitter<boolean>();
    @Output() manageEquipmentChange = new EventEmitter<ManageEquipment>();
    @Output() getData = new EventEmitter();
    selectType: any;
    selectId: any;
    selectStatus: any;
    selectConnectionStatus: any;
    Photograph = [];
    imgFormatLimit = {
        size: 9, // 单位M
        type: ['png', 'jpg', 'jpeg'],
        dimension: [9999999998, 9999999999] // [宽，高]
    };
    isForce = false;
    isForceVisible = false;
    zoneIdList = [];
    clickBtn = null;
    subscription: Subscription = null;
    // 初始化表单
    @Input()
    set manageEquipment(value: ManageEquipment) {
        this.selectId = value.id;
        this.selectType = value.type;
        this.selectStatus = value.status;
        this.selectConnectionStatus = value.connectionStatus;
        this.Photograph = value.url ? value.url.split(',') : [];
        if (!value.hasOwnProperty('status')) {
            value['status'] = 'Active';
        }
        if (!value.hasOwnProperty('connectionStatus')) {
            value['connectionStatus'] = null;
        }
        this.formDataInit(value);
    }

    equipmentInfoForm: FormGroup;

    @Input() isTaskFromGis = false;
    @Output() positionNewDevice = new EventEmitter<any>();
    constructor(
        private fb: FormBuilder,
        public eqt: EquipmentService,
        private msg: NotificationService,
        private message: NzMessageService,
        private ss: SystemService,
        private authService: AuthService,
        private msgErr: MessagesService,
        private bully: BullySubjectService,
        private incidentService: IncidentService
    ) {
        this.equipmentInfoForm = this.fb.group({
            id: [{ value: null, disabled: false }, Validators.required],
            nextDate: [{ value: null, disabled: false }],
            type: [{ value: null, disabled: false }],
            supervision: [{ value: null, disabled: false }],
            ip: [{ value: null, disabled: false }, [this.ipValidate]],
            installDate: [{ value: null, disabled: false }],
            zoneID: [{ value: null, disabled: true }],
            constructionUnit: [{ value: null, disabled: false }],
            longitude: [{ value: null, disabled: false }, Validators.required],
            constructionPerson: [{ value: null, disabled: false }],
            latitude: [{ value: null, disabled: false }, Validators.required],
            roadName: [{ value: null, disabled: false }],
            direction: [{ value: null, disabled: false }],
            url: [{ value: null, disabled: false }],
            status: [{ value: 'Active', disabled: false }],
            connectionStatus: [{ value: null, disabled: false }]
        });
    }

    ngAfterViewInit(): void {
        this.equipmentInfoForm.get('longitude').valueChanges.subscribe(coorStr => {
            if (coorStr && this.equipmentInfoForm.get('latitude').value) {
                this.getZoneIdFromPos({ posX: this.equipmentInfoForm.get('latitude').value, posY: coorStr });
            }
        });
        this.equipmentInfoForm.get('latitude').valueChanges.subscribe(coorStr => {
            if (coorStr && this.equipmentInfoForm.get('longitude').value) {
                this.getZoneIdFromPos({ posX: coorStr, posY: this.equipmentInfoForm.get('longitude').value });
            }
        });
    }

    private getZoneIdFromPos(pos: { posX: number; posY: number }) {
        this.incidentService.getZoneIdFromGis(pos).subscribe(res => {
            if (!+res) {
                return;
            }
            this.equipmentInfoForm.get('zoneID').setValue(res);
        });
    }

    ipValidate(g: FormControl) {
        if (g.value) {
            const ip = g.value;
            const reg = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g;
            return reg.test(ip) ? null : { ip: true };
        }
    }
    private formDataInit(value: ManageEquipment) {
        this.equipmentInfoForm.setValue(value);
        // title.split('_')[0] === 'Edit'?true:false
        if (this.title.split('_')[0] === 'Edit') {
            this.equipmentInfoForm.get('type').disable();
            this.equipmentInfoForm.get('id').disable();
        }
    }

    close(e?) {
        if (this.title === 'Add_Equipment') {
            const { url } = this.equipmentInfoForm.value;
            if (url) {
                url.forEach(item => {
                    if (item && !e) {
                        this.deleteOriginImg(item);
                    }
                });
            }
        }
        // this.deleteOriginImg();
        this.visible = false;
        this.visibleChange.emit(this.visible);
    }

    // cancel 按钮
    handleCancel() {
        this.close();
    }
    // 删除替换图片
    deleteOriginImg(url) {
        this.eqt.deleteImgByUrl(url).subscribe(res => {});
    }
    // 取消强制操作
    FourchHandleCancel() {
        this.isForceVisible = false;
    }
    // 确定强制操作
    ForceHandleOk() {
        this.isForceVisible = false;
        this.isForce = true;
        this.handleOk();
    }
    // 获取用户的ZoneIdList
    getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.eqt.getAllUser(queryData).subscribe(res => {
            const userZone = res.content.content[0].userZoneRel;
            userZone.forEach(zoneId => {
                this.zoneIdList.push(zoneId.vnqn_zone_id);
            });
        });
    }
    // 确定按钮
    handleOk() {
        this.submitForm();
        const zoneIds = this.ss.userZoneList.filter(z => !z.isTemp).map(z => z.id);
        const header = {
            zoneId: zoneIds.join(','),
            isFource: this.isForce
        };
        if (this.equipmentInfoForm.valid) {
            const manageEquipment = this.equipmentInfoForm.getRawValue();
            this.manageEquipmentChange.emit(manageEquipment);
            this.isOkLoading = true;
            if (this.title === 'Add_Equipment') {
                if (manageEquipment.zoneID && !this.authService.isUserZoneChecked(manageEquipment.zoneID)) {
                    this.isOkLoading = false;
                    return;
                }
                this.eqt.postCreateDevice(manageEquipment, header).subscribe(res => {
                    this.isOkLoading = false;
                    if (res['code'] === '900101') {
                        this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.create_notify' });
                        return;
                    }
                    if (res['code'] === '900103') {
                        this.isForceVisible = true;
                    }
                    if (res['code'] === '900104') {
                        this.msgErr.error(res['msg']);
                    }
                    if (res['code'] === '000000') {
                        if (this.isTaskFromGis) {
                            this.positionNewDevice.emit(res['data']);
                        }
                        this.close(true);
                        this.getData.emit();
                    }
                }, err => (this.isOkLoading = false));
            } else {
                manageEquipment.id = this.selectId;
                manageEquipment.type = this.selectType;
                manageEquipment.status = this.selectStatus;
                manageEquipment.connectionStatus = this.selectConnectionStatus;
                this.eqt.postUpdateDevice(manageEquipment, header).subscribe(res => {
                    // this.close(true);
                    this.isOkLoading = false;
                    // this.getData.emit();
                    if (res['code'] === '900103') {
                        this.isForceVisible = true;
                    } else {
                        if (res['code'] !== '000000') {
                            this.message.create('error', res.msg);
                        }
                        this.close(true);
                        this.isOkLoading = false;
                        this.getData.emit();
                    }
                }, err => (this.isOkLoading = false));
            }
        }
    }
    submitForm(): void {
        // tslint:disable-next-line:forin
        for (const i in this.equipmentInfoForm.controls) {
            if (this.equipmentInfoForm.controls.hasOwnProperty(i)) {
                this.equipmentInfoForm.controls[i].markAsDirty();
                this.equipmentInfoForm.controls[i].updateValueAndValidity();
            }
        }
    }
    getImgData(event, index) {
        this.Photograph[index] = event.url;
        const data = {
            id: this.selectId,
            type: this.selectType,
            ...this.equipmentInfoForm.getRawValue(),
            url: this.Photograph
        };
        this.equipmentInfoForm.setValue(data);
    }
    // 获取上传图片的状态
    getUploadStatus(status) {
        switch (status) {
            case 'type': {
                this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.validate_format' });
                break;
            }
            case 'size': {
                this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.validate_size' });
                break;
            }
            case 'dimension': {
                this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.validate_dimension' });
                break;
            }
        }
    }
    ngOnInit() {
        this.getZoneIdListByUser();
        this._setGisPosition();
    }

    ngOnDestroy() {
        this.bully.resetBSubject();
        if (this.subscription) {
            this.bully.resetBSubject();
            this.subscription.unsubscribe();
        }
    }

    getGisPosition(key) {
        this.clickBtn = key;
        const bully = {
            type: MESSAGE_CHANNEL.CCM_CHANNEL,
            data: {
                data: key
            }
        };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, bully);
    }

    private _setGisPosition() {
        this.subscription = this.bully.registerBroadcastReceive(MESSAGE_CHANNEL.MAP_CHANNEL).subscribe(res => {
            if (res.type === MESSAGE_CHANNEL.MAP_CHANNEL) {
                const features = res['data']['features'];
                this.clickBtn = null;
                const value = {
                    longitude: features['longitude'],
                    latitude: features['latitude'],
                    roadName: features['roadName']
                };
                this.equipmentInfoForm.patchValue(value);
            }
        });
    }
}
